import { eHotUpdateEvent } from "../update/HotUpdateEvent";
import { SubGameHotUpdate } from "../update/SubGameHotUpdate";
import { g_bundleName } from "./assetsManager";
import GameMgr from "./gameManager";
import SoundMgr from "./soundManager";




/**
 * 子游戏信息
 */
export interface SubGameData {
    name: string;
    sceneName: string;
    packageUrl: string;
    rankType: string;
    gameName?: string;
}



class SubGameMgrClass {
    /**
     * 正在运行的子游戏
     */
    runningSubGame: string = "";

    /**
     * 正在加载的子游戏
     */
    loadingSubGame: string = "";

    /**
     * 子游戏更新管理器
     */
    subGameHotUpdateCtrls: { [key: string]: SubGameHotUpdate } = {};

    /**
     * 子游戏Bundle
     */
    subGameBundles: { [key: string]: cc.AssetManager.Bundle } = {};

    fireGameBegin = false;
    log(...arg) {
        CC_DEBUG && console.log("[SubGameMgr]", ...arg);
    }

    /**
     * 启动子游戏
     * @param subGameName 子游戏名
     */
    launchSubGame(bundleName: string, sceneName: string) {

        if (this.fireGameBegin && bundleName === 'gameFire') {
            GameMgr.Ins().showMsg("此游戏不支持重复进入,请先重启app再启动此游戏", "重启", '取消', () => {
                cc.game.end();
                this.fireGameBegin = false;
            })
            return;
        }


        if (this.loadingSubGame) {
            this.log("有子游戏正在加载：", this.loadingSubGame);
            return;
        }
        if (this.runningSubGame == bundleName) {
            this.log("当前子游戏正在运行：", this.runningSubGame);
            return;
        }
        if (CC_JSB && this.subGameHotUpdateCtrls[bundleName] && this.subGameHotUpdateCtrls[bundleName]._updating) {
            this.log("当前子游戏正在更新中");
            return;
        }
        this.exitSubGame(this.runningSubGame);
        this.loadingSubGame = bundleName;
        if (CC_JSB) {

            cc.assetManager.loadBundle(bundleName, {}, (err, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    throw err;
                }
                this.subGameBundles[bundleName] = bundle;



                bundle.loadScene(sceneName, async (err, sceneAsset: cc.SceneAsset) => {
                    if (err) {
                        throw err;
                    }


                    cc.director.runScene(sceneAsset, null, () => {
                        this.runningSubGame = bundleName;
                        this.loadingSubGame = "";
                        // SoundMgr.Ins().initAudioclip(bundleName, 'music');
                    });
                });
            });

            // VersionTool.getSubGameVersion(subGameName).then((version) => {

            // });
        } else {
            cc.assetManager.loadBundle(bundleName, (err, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    throw err;
                }
                this.subGameBundles[bundleName] = bundle;



                bundle.loadScene(sceneName, (err, sceneAsset: cc.SceneAsset) => {
                    if (err) {
                        throw err;
                    }
                    cc.director.runScene(sceneAsset, null, () => {
                        this.runningSubGame = bundleName;
                        this.loadingSubGame = "";
                        // SoundMgr.Ins().initAudioclip(bundleName, 'music');
                    });
                });
            });
        }
    }

    /**
     * 退出子游戏
     *
     * 这里只执行资源释放 如需跳转场景需自行跳转
     * @param subGameName 为空则退出当前运行的子游戏
     */
    exitSubGame(subGameName?: string) {

        if (!subGameName) {
            subGameName = this.runningSubGame;
        }
        this.log("退出子游戏:", subGameName, this.runningSubGame);
        if (subGameName !== 'gameEat') {
            this.releaseSubGame(subGameName);
        }

        if (subGameName === 'gameFire') {
            this.fireGameBegin = true;
        }

        this.runningSubGame = "";
        this.loadingSubGame = "";
        this.subGameHotUpdateCtrls[subGameName] = null;
        cc.systemEvent.targetOff(this);

    }

    /**
     * 释放子游戏，通常在更新完子游戏后需要释放重新加载
     */
    releaseSubGame(subGameName: string) {
        let subGameBundle = this.subGameBundles[subGameName];
        if (subGameBundle) {
            SoundMgr.Ins().releaseAucioclip(subGameName);
            subGameBundle.releaseAll();
            cc.assetManager.removeBundle(subGameBundle);
        }
        this.subGameBundles[subGameName] = null;
    }





    async loadRes(bundleName: string, resName: string): Promise<cc.Asset> {
        const bundle = this.subGameBundles[bundleName];
        if (!bundle) {
            console.log('bundleName not found:', bundleName);
            return;
        }


        return new Promise<cc.Asset>((res, rej) => {
            bundle.load(resName, (err: Error, assets: any) => {
                if (err) {
                    console.log(err);
                    rej(err);
                } else {
                    console.log("loadRes success", assets.name);
                    res(assets);
                }
            });
        });
    }

    /**
     * 获取子游戏更新控制器
     *
     * 没有默认会生成一个
     * @param subGameName
     * @returns
     */
    async getSubGameHotUpdateCtrl(subGameName: string, packageUrl: string) {
        let ctrl = this.subGameHotUpdateCtrls[subGameName];
        if (!ctrl) {
            try {
                ctrl = new SubGameHotUpdate();
                await ctrl.init(subGameName, packageUrl);
                this.subGameHotUpdateCtrls[subGameName] = ctrl;
            } catch (error) {
                throw error;
            }
        }
        return ctrl;
    }

    /**
     * 检查子游戏是否有更新
     * @param subGameName
     */
    async checkUpdateSubGame(subGameName: string, packageUrl: string) {
        this.log(`子游戏${subGameName}检查更新,url:${packageUrl}`);
        if (!CC_JSB) {
            return;
        }
        if (CC_JSB && this.subGameHotUpdateCtrls[subGameName] && this.subGameHotUpdateCtrls[subGameName]._updating) {
            this.log("当前子游戏正在更新中");
            return;
        }
        if (CC_JSB && this.subGameHotUpdateCtrls[subGameName] && this.subGameHotUpdateCtrls[subGameName].canUpdate) {
            this.log("当前子游戏可更新");
            cc.systemEvent.emit(eHotUpdateEvent.subGameCheckVersionResult + subGameName, true);
            return;
        }
        try {
            let ctrl = await this.getSubGameHotUpdateCtrl(subGameName, packageUrl);
            cc.systemEvent.once(eHotUpdateEvent.subGameCheckVersionResult + subGameName, (newVersionFound) => {
                if (!newVersionFound) {
                    this.subGameHotUpdateCtrls[subGameName] = null;
                }
            });
            ctrl.checkUpdate();
        } catch (error) {
            throw error;
        }
    }

    /**
     * 更新子游戏
     * @param subGameName
     */
    hotUpdateSubGame(subGameName: string) {
        if (!CC_JSB) {
            return;
        }
        let ctrl = this.subGameHotUpdateCtrls[subGameName];
        console.log(`${subGameName} ctrl  `)
        if (ctrl) {
            cc.systemEvent.once(eHotUpdateEvent.subGameHotUpdateFinish + subGameName, () => {
                // 更新完成
                this.releaseSubGame(subGameName);
                this.subGameHotUpdateCtrls[subGameName] = null;
            });
            ctrl.hotUpdate();
        }
    }
}

/**
 * 子游戏管理器
 */
export const subGameMgr = new SubGameMgrClass();
